<template>
  <div class="top flex-center">
    <div class="back flex-center hover-light" v-show="!newSurveyData.submitting" @click="$router.push('/home')">
      <BackSvg />
      <span class="text-padding">回到首页</span>
    </div>

    <div class="config">
      <div class="btn-item">
        <button @click="exportSurvey"> <span>导出模板</span> </button>
      </div>
      <div class="btn-item import-file">
        <button>
          <input type="file" accept="application/json" @change="importSurvey" />
          <span>导入模板</span>
        </button>
      </div>
      <div class="btn-item" v-show="!newSurveyData.created">
        <button @click="clearData"> <span>重置问卷</span> </button>
      </div>
    </div>

    <div class="btn-frame btn-submit" v-show="!newSurveyData.created">
      <button class="custom-btn btn-primary" :class="{forbidden: newSurveyData.submitting}" @click="submitSurvey">
        <span v-show="!newSurveyData.submitting">创建问卷</span>
        <span v-show="newSurveyData.submitting"> 上传中... </span>
      </button>
    </div>
  </div>
</template>

<script>
import useNewSurveyData from '@/store/new-survey-data'
import postSurvey from '@/request/postSurvey'
import { isNil } from '@/utils/utils'
import download from '@/utils/download'

export default {
  data: () => ({
    newSurveyData: useNewSurveyData(),
  }),
  methods: {
    async submitSurvey() {
      const data = {
        title: this.newSurveyData.title,
        info: this.newSurveyData.info,
        questions: JSON.parse(JSON.stringify(this.newSurveyData.questions)),
      }
      if (this.isIllegal(data))
        return
      try {
        this.newSurveyData.submitting = true
        const res = await postSurvey(data)
        if (res.status === "success") {
          this.$msg("创建成功", "success")
          this.newSurveyData.created = true
          this.newSurveyData.surveyUrl = window.location.origin + `/fill-in/${res.id}`
        }
        else {
          this.$msg(res.data, "error")
        }
      }
      catch (error) {
        this.$msg(error.message, "error")
      }
      this.newSurveyData.submitting = false
    },
    isIllegal({ title, questions: qs }) {
      if (isNil(title)) {
        this.$msg("请输入问卷标题", "error")
        return true
      }
      for (let i = 0; i < qs.length; i++) {
        if (isNil(qs[i].title)) {
          this.$msg(`问题中的标题不允许为空（第 ${i + 1} 个问题）`, "error")
          return true
        }
        if (qs[i]?.options && isNil(qs[i].options)) {
          this.$msg(`问题中的选项不允许为空（第 ${i + 1} 个问题）`, "error")
          return true
        }
        if (qs[i]?.subTitles && isNil(qs[i].subTitles)) {
          this.$msg(`第 ${i + 1} 个问题的小标题不允许为空`, "error")
          return true
        }
      }
      return false
    },
    clearData() {
      if (window.confirm("确定清除缓存吗？清除后当前页面的问卷数据会消失"))
        this.newSurveyData.clearData()
    },
    exportSurvey() {
      const data = {
        survey_title: window.localStorage.getItem('survey_title') || '',
        survey_info: window.localStorage.getItem('survey_info') || '',
        survey_questions: JSON.parse(window.localStorage.getItem('survey_questions')) || [],
      }
      const fileName = (window.localStorage.getItem('survey_title') || 'survey-template') + '.json'
      const type = 'application/json'
      const blob = new Blob([JSON.stringify(data)], { type })
      download({ blob, fileName })
    },
    async importSurvey(e) {
      e.target.files[0]?.text && this.newSurveyData.importData(JSON.parse(await e.target.files[0].text()))
    },
  },
}
</script>

<style lang="scss" scoped>
.top {

  width: 100%;
  height: 80px;
  padding: 0 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #aaa;

  overflow: auto;
  overflow-y: hidden;

  position: fixed;
  z-index: 100;
  top: 0;
  left: 0;

  display: flex;
  align-items: center;
  justify-content: space-between;

  background-color: #fff;

  .back {
    flex: none;

    height: 40px;
    width: 140px;
  }

  .config {
    flex: none;

    width: max-content;
    margin: auto 10px;

    display: flex;
    align-items: center;
    justify-content: center;

    .btn-item {
      flex: none;

      width: 100px;
      margin: 0 5px;

      display: grid;
      place-content: center;
    }

    .import-file {
      button {
        position: relative;
        input[type="file"] {
          opacity: 0;
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
        }
      }

    }
  }

  .btn-submit {
    flex: none;

    width: 150px;
    margin: 10px;

    display: grid;
    place-content: center;
  }
}
</style>
